package com.winit.projectPlan.repository;

import com.winit.projectPlan.model.Task;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;

@Component
public class TaskRepositoryExt {
    private static Logger log = LoggerFactory.getLogger(TaskRepositoryExt.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void updatePropertiesNotNull(Task task){
        Task entity = entityManager.find(Task.class, task.getId());
        if (entity == null){
            log.error("no task found for project_plan_id:" + task.getId() + ", updating aborted");
            return;
        }
        if (task.getChargerAccount() != null){
            entity.setChargerAccount(task.getChargerAccount());
        }
        if (task.getChargerRealname() != null){
            entity.setChargerRealname(task.getChargerRealname());
        }
        if (task.getContent() != null){
            entity.setContent(task.getContent());
        }
        if (task.getCreaterAccount() != null){
            entity.setCreaterAccount(task.getCreaterAccount());
        }
        if (task.getCreaterRealname() != null){
            entity.setCreaterRealname(task.getCreaterRealname());
        }
        if (task.getNumber() != null){
            entity.setNumber(task.getNumber());
        }
        if (task.getStatus() != null){
            entity.setStatus(task.getStatus());
        }
        if (task.getType() != null){
            entity.setType(task.getType());
        }
        if (task.getWorkHours() != null){
            entity.setWorkHours(task.getWorkHours());
        }
        if(task.getStartupTime()!=null){
            entity.setStartupTime(task.getStartupTime());
        }
        entityManager.merge(entity);
        entityManager.flush();
    }


    public List<Map<String, Object>> getMemberTaskStats(String projectPlanId){
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT charger_account AS chargerAccount, charger_realname AS chargerRealname, count(1) AS taskNum, status  FROM matrix_task");
        if ((!StringUtils.isEmpty(projectPlanId))){
            sql.append(" WHERE project_plan_id =  '") ;
            sql.append(projectPlanId);
            sql.append("' ");
        }
        sql.append(" GROUP BY charger_account, status");
        Session session = entityManager.unwrap(Session.class);
        return session.createSQLQuery(sql.toString()).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
    }
}
